import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import { showScreenLoading, hideScreenLoading } from "./loading";


// create an axios instance
const service = axios.create({
  timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // if(JSON.stringify(config.data).indexOf('TestMailGlobal')!== -1){
    //   hideScreenLoading(config.headers);
    // }
    if (config.headers.showLoading !== false) {
      showScreenLoading(config.headers);
    }
    
    return config
  },
  error => {
    hideScreenLoading(config.headers);
    console.log(error,100) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (response.headers.showLoading !== false) {
      hideScreenLoading();
    }
    let isdownload = response.request.responseURL.indexOf('download') //下载接口没有StatusCode 
    let isupload = response.request.responseURL.indexOf('upload') //上传接口没有StatusCode
    const res = response.data
    if (isdownload === -1 && isupload === -1 && res.Status.StatusCode !== 0) {  //
      if (res.Status.StatusCode === 2000) {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
        // to re-login
        // MessageBox.confirm('登录状态已失效，是否重新登录', {
        //   confirmButtonText: '重新登录',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   store.dispatch('user/resetToken').then(() => {
        //     location.reload()
        //   })
        // })
      }else if(res.Status.StatusCode === 12557){
        Message({
          message: '您的授权已经过期超过15天，系统禁止登录，请您联系您的服务商。',
          type: 'error',
          duration: 5 * 1000
        })
      }else if(res.Status.StatusCode === 256){  //邮箱测试接口返回256，错误0x100
        return res
      }else{
        Message({
          message: res.Status.Msg2Client || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.Status.Msg2Client || 'Error'))
    } else {
      return res
    }
  },
  error => {
    hideScreenLoading();
    console.log('err' + error) // for debug
    Message({
      message: error.message === 'timeout of 50000ms exceeded' ? '请求超时' : error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
